'use strict';

angular.module('com.dcos.app').controller('WorkFlowCreateController', function($rootScope,$window,$scope,$state,$stateParams, $filter, api, $uibModal, WorkFlowCreateService,TemplateService,TemplateDetailService) {
  var vm = this;

  vm.breadCrumbArr = [api.breadCrumbMap.workflow.root,api.breadCrumbMap.workflow.create.root];

  $scope.propertydata=[];

  vm.formdata = {};

  vm.curProjectId=$window.sessionStorage.getItem("curProjectId");
  vm.userid=$window.sessionStorage.getItem("curUserId");

  // if(!vm.userid)
  //   $state.go('login');
  
  vm.pipeline=true;

  vm.menudata=[];

  vm.curNodeId="";

  $scope.flowdata={};
  
  $scope.p_name = "";

  vm.p_id=$stateParams.p_id;

  if(!vm.p_id)
  	vm.p_id='';
	vm.template={
    "p_id":vm.p_id,
    "t_name":"",
    "project_id":vm.curProjectId,
    "description":"",
    "status":"1",
    "create_user":vm.userid
  };
  
  function fnInit() {
//    vm.menudata =
//        [
//        	{header:"控制流",isopen:true,plugin:[
//            	{plugin_id:1,business_type:0,node_type:1,icon_src:"../../images/flowconfig/start",plugin_name:"start",plugin_type:1},
//            	{plugin_id:2,business_type:0,node_type:2,icon_src:"../../images/flowconfig/end",plugin_name:"endNode",plugin_type:2}]},
//      	{header:"代码仓库",isopen:true,plugin:[
//            	{plugin_id:3,business_type:1,node_type:1,icon_src:"../../images/flowconfig/git",plugin_name:"git",plugin_type:1},
//            	{plugin_id:4,business_type:1,node_type:2,icon_src:"../../images/flowconfig/svn",plugin_name:"svn",plugin_type:2}]},
//    		{header:"开发语言",isopen:true,plugin:[
//            	{plugin_id:5,business_type:1,node_type:1,icon_src:"../../images/flowconfig/C++",plugin_name:"C++",plugin_type:1},
//            	{plugin_id:6,business_type:1,node_type:2,icon_src:"../../images/flowconfig/golang",plugin_name:"golang",plugin_type:2}]}
//        ];
//    angular.forEach(vm.menudata,function(item,index){
//        angular.forEach(item.plugin,function(_item,_index){
//            vm.propertydata.push(_item);
//        });
//    });
//    vm.flowdata={
//        p_id:1,
//        p_name:'cicd',
//        description:"this is cicd",
//        status:"1",
//        create_user:"szh",
//        project_id:1
//    };
// WorkFlowCreateService.init($scope.curProjectId,vm.p_id).then(function (response) {
//    vm.menudata=response.data.menudata;
//
//
//    angular.forEach(vm.menudata,function(item,index){
//      angular.forEach(item.plugin,function(_item,_index){
//        $scope.propertydata.push(_item);
//      });
//    });
//    console.log($scope.propertydata);
//    $scope.flowdata=response.data.flowdata;
//    $scope.fnInitData();
//  });
		initIndexedDB("workflowsql",function(){
			var transaction = indexeddb.transaction(["plugin","workflow","job"],'readwrite');
			var pluginStore = transaction.objectStore('plugin');
			var pluginRequest = pluginStore.openCursor();
			var plugins = [];
			pluginRequest.onsuccess = function(e){
				var cursor = e.target.result;
				if(cursor){
					var plug = cursor.value;
					plug.plugin_id = plug.id;
					plugins.push(cursor.value);
					$scope.propertydata.push(cursor.value);
					cursor.continue();
				}else{
					var workflowStore = transaction.objectStore('workflow');
					var workflowRequest=workflowStore.openCursor();
					workflowRequest.onsuccess = function(e){
						var cur = e.target.result;
						if(cur){
							var value = cur.value;
							value.plugin = [];
							var pluginids = value.pluginids.split(",");
							for(var i = 0;i<pluginids.length;i++){
								var pluginid = pluginids[i];
								for(var j = 0;j<plugins.length;j++){
									if(plugins[j].id==pluginid){
										value.plugin.push(plugins[j]);
										break;
									}
								}
							}
							vm.menudata.push(value);
							cur.continue();
						}else{
							if(vm.p_id!=""){
								//根据p_id获取job信息
								var jobStore = transaction.objectStore('job');
								var jobIndex = jobStore.index('p_id');
								var range = IDBKeyRange.only(vm.p_id);
								jobIndex.openCursor(range).onsuccess = function(e){
									$scope.flowdata=e.target.result.value;
									$scope.fnInitData();
								}
							}else{
								$scope.flowdata={"p_name":""};
								$scope.fnInitData();
							}
							
						}
					}
				}
			}
		});
  }

  fnInit();

  $scope.fnSave = function (data) {
    data.p_name = $("#pip_name")[0].value.trim();
    data.p_id = guid();
		data.create_time = getNowDate();
    if(data.p_name){
        $rootScope.loading = true;
//      WorkFlowCreateService.save(data).then(function (response) {
//        $state.go('app.workflow', {}, { reload: true });
//        data.p_id=response.data.data.p_id;
//        data.p_name=response.data.data.p_name;
//        vm.p_id=data.p_id;
//        vm.template.p_id=vm.p_id;
//        $rootScope.loading=false;
//    });
      var transaction = indexeddb.transaction("job", "readwrite");
			var store = transaction.objectStore('job');
			var request = store.add(data);
			request.onsuccess=function(event){
				$state.go('app.workflow', {}, { reload: true });
          data.p_id=data.p_id;
          data.p_name=data.p_name;
          vm.p_id=data.p_id;
          vm.template.p_id=vm.p_id;
          $rootScope.loading=false;
			}
    }else{
        var modalInstance = $uibModal.open({
          animation: true,
          templateUrl: '../../controllers/workflow/create/alert/alert.html',
          controller: 'AlertController as vm',
          resolve: {
          }
        });
    }
  }
  $scope.fnCreateTemplate = function () {
    var modalInstance = $uibModal.open({
      animation: true,
      templateUrl: 'controllers/workflow/create/template/create.html',
      controller: 'TemplateNameController as vm',
      resolve: {
        save:function(){return $scope.fnSaveTemplate;},
        savedata:function(){return $scope.vm.template;},
        templateName:function(){return null;}
      }
    });
  }
    $scope.fnSaveTemplate = function (data) {
    $rootScope.loading = true;
    TemplateService.saveByPipeLine(data).then(function (response) {
      $rootScope.loading = false;
      $state.go('app.workflow', {}, { reload: true });
    });
  }
  $scope.fnRun = function () {
    $state.go('app.workflow.build', {'p_id':vm.p_id});
  }
});

